package org.chen.ctrip.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.chen.common.ctrip.crawler.CrawlRequest;
import org.chen.common.ctrip.dto.AiProductResponse;
import org.chen.common.ctrip.dto.ProductCreateContentRequest;
import org.chen.common.ctrip.dto.ProductRequest;
import org.chen.common.ctrip.entity.Product;
import org.chen.common.result.ResultVO;
import org.chen.ctrip.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/products")
@Tag(name = "不重要的接口", description = "不重要的接口")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("/crawl")
    @Tag(name = "线路查询接口")
    public ResultVO crawlProducts(@RequestBody CrawlRequest crawlRequest) {

        try {
            List<Product> product = productService.crawlProducts(crawlRequest);
            return ResultVO.success("爬取任务已启动", product);
        } catch (Exception e) {
            return ResultVO.fail("爬取失败" + e.getMessage());
        }

    }

    @PostMapping("/fetch-detail/{productId}")
    public ResultVO fetchProductDetail(@PathVariable String productId) {
        try {
            Product product = productService.fetchProductDetail(productId);
            return ResultVO.success("详情获取完成", product);
        } catch (Exception e) {
            return ResultVO.fail("获取详情失败: " + e.getMessage());
        }

    }

    @GetMapping("/syncData")
    public ResultVO syncData() {
        productService.syncData();
        return ResultVO.success();
    }

    @GetMapping
    public ResultVO getProducts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String productType,
            @RequestParam(required = false) Boolean detailFetched) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 构建查询条件
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            if (StringUtils.hasText(title)) {
                wrapper.like("title", title);
            }
            if (StringUtils.hasText(productType)) {
                wrapper.eq("product_type", productType);
            }
            if (detailFetched != null) {
                wrapper.eq("detail_fetched", detailFetched);
            }
            wrapper.orderByDesc("update_time");

            // 分页查询
            Page<Product> pageParam = new Page<>(page, size);
            IPage<Product> pageResult = productService.page(pageParam, wrapper);

            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            result.put("pages", pageResult.getPages());
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.fail("查询失败: " + e.getMessage());
        }

    }

    @GetMapping("/{id}")
    @Tag(name = "获取商品详情")
    public ResultVO getProduct(@PathVariable("id") String id,
                               @RequestParam(value = "lang", required = false) String lang) {
        try {
            Product product = productService.getByIdAndLanguage(id, lang);
            if (product != null) {
                return ResultVO.success(product);
            } else {
                return ResultVO.fail("商品不存在");
            }
        } catch (Exception e) {
            return ResultVO.fail("查询失败: " + e.getMessage());
        }

    }



    @PostMapping("/updateContent")
    @Tag(name = "更新商品内容")
    public ResultVO updateContent(@RequestBody ProductRequest productRequest) {

        try {
            Product product = productService.updateProduct(productRequest);
            if (product != null) {
                return ResultVO.success(product);
            } else {
                return ResultVO.fail("更新失败，商品可能不存在或数据不完整");
            }
        } catch (Exception e) {
            return ResultVO.fail("更新失败: " + e.getMessage());
        }

    }

    @PostMapping("/createContent")
    @Tag(name = "创建商品内容")
    public ResultVO createContent(@RequestBody ProductCreateContentRequest productCreateContentRequest) {

        try {
            AiProductResponse product = productService.createContent(productCreateContentRequest);
            if (product != null) {
                return ResultVO.success(product);
            } else {
                return ResultVO.fail("创建失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("创建失败: " + e.getMessage());
        }

    }

    @DeleteMapping("/{id}")
    @Tag(name = "删除商品")
    public ResultVO deleteContent(@PathVariable String id) {

        try {
            boolean product = productService.deleteContentById(id);
            if (product) {
                return ResultVO.success("删除成功");
            } else {
                return ResultVO.fail("删除失败，商品可能不存在");
            }
        } catch (Exception e) {
            return ResultVO.fail("删除失败: " + e.getMessage());
        }
    }
}